﻿ (function($) {

$.voting = {};

$.voting.initialized = false;

$.voting.paused = false;

$.voting.init = function()
{
    if ($.voting.initialized)
        return;

    $.voting.initialized = true;

    $.post('voting-new-element-template.html', null, function(data) { $.voting.elementTemplate = $(data); } ,'html');

    $.post('voting-comment-template.html', null, function(data) { $.voting.commentTemplate = $(data); },'html');

	$("#scrollableAreaContent").scroll($.voting.onScroll);
	
	$.voting.load();
	
	setInterval($.voting.refresh, 2000);	
}

$.voting.load = function(direction)
{
	if(!direction)
		direction = 0
		
	if(!$.voting.olderCombinationId)
		$.voting.olderCombinationId = 0;
		
	if(!$.voting.newerCombinationId)
		$.voting.newerCombinationId = 0;

	$.post("./bus/load_voting.php", 
		"olderCombinationId=" + $.voting.olderCombinationId +
		"&newerCombinationId=" + $.voting.newerCombinationId + 
		"&direction=" + direction,

	function(data)
	{
		if(data.Elements && $.voting.newerCombinationId < data.Elements[0].CombinationId)
			$.voting.newerCombinationId = data.Elements[0].CombinationId;
	
		for(var item in data.Elements)
		{
			$.voting.newVoting(data.Elements[item], direction);
			
			if($.voting.olderCombinationId==0 || $.voting.olderCombinationId > data.Elements[item].CombinationId)
				$.voting.olderCombinationId = data.Elements[item].CombinationId;
		}
	});
}

$.voting.newVoting = function(element, direction)
{
	var $clone = $(".voting-item[combinationId=" +element.CombinationId+"]");
	
	if($clone.length == 0)
	{	
		$clone = $.voting.elementTemplate.clone();
		
		$clone.attr('combinationId', element.CombinationId);
		
		if(direction == 0)
		{
			$("#voting").append($clone);
			
			$clone.verticalShow();
		}
		else
		{
			$("#voting").prepend($clone);
			
			$clone.verticalShow();
		}
		
		if(element.Votes.AuthorId == $.cookie('Id'))
			$(".button", $clone).addClass("ui-state-active"); 
			
		$("textarea", $clone).keypress(function(e)
		{
			if(e.which == 13)
			{
				$.voting.Comment($(this), element.CombinationId);
				e.preventDefault();
			}
		}).enableSelection();
		
		$clone.disableSelection();
		
		$(".button", $clone).click(function()
		{
			$.voting.vote(element, $(this));
		});
	}

	$clone.attr('invalidate', 0);

	//newElementPic
	$(".time", $clone).html($.createdAt(element.CreateDate));
	$(".user", $clone).html(element.UserName);
	
	//elements = element.ElementId
	//TODO:Wow it
	var msg = "Thinks [" + element.Elements.Name[0] + "] with [" + element.Elements.Name[1] + "] gives [" + element.ProductName + "].";	
	
	$(".message", $clone).html(msg);
	
	//TODO:$("#newElementTags", $clone).html(element.UserName);
	msg = "Be the first to vote.";
	
	if(element.Votes.Value == 0)
		msg = element.Votes.Name + " up this.";
	else if 	(element.Votes.Value > 0)
		msg = element.Votes.Name + " and " + element.Votes.Value + " more up this.";
	
	$(".uppers", $clone).html(msg);

	for(var i=0;i<element.Comments.length;i++)
	{
		if(element.Comments.length > 3)
		{
			if(i > 1 && i<element.Comments.length-1)
			{
				
				if(i < 5)
				{
					$.voting.newVotingComment(element.Comments[i], $clone, element.CombinationId, element.Comments[i].Id, 'collapse');
				}
				else
				{
					$.voting.newVotingComment(element.Comments[i], $clone, element.CombinationId, element.Comments[i].Id, 'hide');
				}
				
			}
			else
				$.voting.newVotingComment(element.Comments[i], $clone, element.CombinationId, element.Comments[i].Id, 'show');
		}
		
	}
}

$.voting.Vote = function(element, $t)
{

	var query = "combinationId=" + element.CombinationId +
		"&vote=1";

	$.post("./bus/new_comment.php", query, function(data)
	{
		if(data.sucess)
		{
		
			if(data.msg == "down")
			{
				$t.removeClass("ui-state-active");
				
				$(".uppers", $t.parent()).html("You un-up this.");
				
				return;
			}
			else
			{
				$(".uppers", $t.parent()).html("You up this.");
				
				$t.addClass("ui-state-active"); 
			}

			data.Vote.Name = $.cookie("Name");
			data.Vote.CreateDate = 0;
		}			
	});
}

$.voting.Comment = function($t, combinationId, voteId)
{
	if(!voteId)
		voteId = 0;

	if($t.val().length == 0 && voteId == 0)
		return;

		
	var query = "combinationId=" + combinationId +
		"&voteId=" + voteId +
		"&message=" + $t.val();
		
	$.post("./bus/new_comment.php", query, function(data)
	{
		if(data.sucess)
		{
			if(voteId == 0)
			{
				data.Vote.Name ="Me";
				data.Vote.CreateDate = 0;
				data.Vote.AuthorId = $.cookie('Id');
			
				$.voting.newVotingComment(data.Vote, $t.parent().parent().parent(), combinationId, data.Vote.Id);
				
				$t.val('');
			}
			
			if(data.delete == "delete")
			{
				$t.parent().parent().verticalHide();
			}
		}
	});
}

$.voting.newVotingComment = function(comment, $newElement, combinationId, voteId, mode)
{
	var $clone = $(".voting-item-comment[voteId=" +voteId+"]");
	
	if($clone.length == 0)
	{	
		$clone = $.voting.commentTemplate.clone();
		
		$clone.attr('voteId', voteId);
		
		if(mode == 'hide')
			$clone.css('display', 'none').attr('mode', 'collapse');
		
		$("div.voting-item-comment-text:last", $newElement).before($clone);
	
		if(mode == 'collapse')
		{
			$clone.css('height', '8').
			css('overflow', 'hidden').
			css('cursor', 'pointer').
			attr('mode', 'collapse').
			css('margin-left', 2).
			click(function()
			{
				$(".voting-item-comment[mode=collapse], .voting-item-comment[mode=hide]",  $newElement).
					hide().
					css('height', '').
					css('margin-left', '').
					css('cursor', '').
					verticalShow().
					unbind('click');
			});
			
		}

		if(mode != 'hide')
			$clone.verticalShow();
			
	
		if(comment.AuthorId == $.cookie('Id'))
		{
			$(".message", $clone).click(function()
			{
				var $label = $(this);
				
				$textarea = $("<textarea>");
				
				$textarea.hide().css('min-height', 40);
				
				$t = $(this);
				
				$textarea.css('height', $label.height());
				
				$t.after($textarea);
				
				$(this).parent().css('min-height', $(this).parent().height());
				
				$(this).verticalHide();
				$textarea.verticalShow();
				
					$textarea.val($(this).text())
					.keypress(function(e, t)
					{
						if(e.which == 13)
						{
							$(this).TextMask();
							$.voting.Comment($(this), combinationId, voteId);
							
							$label.html($(this).val());
							$(this).verticalHide();
							$label.verticalShow();
							e.preventDefault();
						}

					})
					.TextMask(null, "Remove comment")
					.blur(function(e, t)
					{
						$(this).verticalHide();
						$label.verticalShow();
						e.preventDefault();
					});
								
				
				
				$textarea.focus();
				$textarea.setCursorPosition($textarea.val().length,1);
				
				
			});
		}
		else
		{
			$(".message", $clone).disableSelection();
		}

		
	}
	
	$clone.attr('invalidate', 0);
	
	//newElementPic
	$(".time", $clone).html($.createdAt(comment.CreateDate));
	
	$(".user", $clone).html(comment.Name);
		
	$(".message", $clone).html(comment.Message);

	return $clone;
}

$.voting.refresh = function()
{
    if($.voting.paused)
        return;

	//TODO:or editing
	//if($('#scrollableAreaContent> #newElementsArea').offset().top != 50)
		//return;
			
		
	if(!$.voting.olderCombinationId)
		$.voting.olderCombinationId = 0;
		
	if(!$.voting.newerCombinationId)
		$.voting.newerCombinationId = 0;

	$.post("./bus/refresh_voting.php", 
		"olderCombinationId=" + $.voting.olderCombinationId +
		"&newerCombinationId=" + $.voting.newerCombinationId,
		function(data)
		{
			$(".newElement, .newElementComment").attr('invalidate', 1);
	
			for(var item in data.Elements)
				$.voting.newVoting(data.Elements[item], 0);
				
			$(".newElement[invalidate=1], .newElementComment[invalidate=1]").not('.newElementShowAll').verticalHide();
		});
}

$.voting.clear = function(direction)
{
    $.voting.newerCombinationId=0;
	$.voting.olderCombinationId=0;
	$(".newElement", "#newElementsArea").remove();
}

$.voting.pause = function()
{
    $.voting.paused = true;
}

$.voting.resume = function()
{
    $.voting.paused = false;
}

$.voting.onScroll = function(t)
{
	var elem = $('#scrollableAreaContent');
		
	var inner = $('#scrollableAreaContent> #newElementsArea');
		
	if ( Math.abs(inner.offset().top) + elem.height() + elem.offset().top >= inner.outerHeight() ) 
		$.voting.loadCurrentPools (0);
}

})(jQuery);

